#include "StdAfx.h"
#include "MemoryManager.h"
#include "BufferConstraint.h"
MemoryManager* MemoryManager::memoryManager = NULL;
MemoryManager::MemoryManager(void)
{

	initial();

}


MemoryManager::~MemoryManager(void)
{

}
MemoryManager* MemoryManager::getInstance()
{
	if(memoryManager==NULL)
	{
		memoryManager = new MemoryManager();
	}
	return memoryManager;
}
void MemoryManager::initial()
{
	this->buffer = (char*)malloc(BUFFER_MAX_SIZE);
	assert(BUFFER_MAX_SIZE % PAGE_SIZE == 0 );
	

	for(int i = 0; i< PAGE_NUMBER ;i++)
	{
		freePageList.push_back(i);
	}
	

	
}
char* MemoryManager::getPageByIndex(int index)
{
	return this->buffer + index * PAGE_SIZE;
}
char* MemoryManager::getOnePage(void)
{
	if(freePageList.size()==0)
	{
		throw std::runtime_error("out of memory");
	}
	int pageIndex = freePageList.front();
	freePageList.pop_front();
	return getPageByIndex(pageIndex);
}
void MemoryManager::releaseOnePage(char* buffer)
{
	assert((buffer - this->buffer)%PAGE_SIZE == 0);
	int index = (buffer - this->buffer)/PAGE_SIZE;
	freePageList.push_front(index);
}

int MemoryManager::getPageSize(void)
{
	return PAGE_SIZE;
}